// pages/luoAn/common/loginIndex.js
const app = getApp()
const config = app.config()
const MRDCommonConst = app.MRDCommonConst()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.wxCodeGet()
  },

  wxCodeGet: async function () {
     
    const code1 = await getApp().CommonHttp().mrjAsyncWXLogin({});
    console.log('code', code1)
    return code1
  },

  /*
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  popMethod: function (e) {
    app.popMethod()
  },
  serviceDetail: function (e) {
    wx.navigateTo({
      url: '/pages/main/my/about/serviceProtocol',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindgetuserinfo: async function (e) {
    console.log('bindgetuserinfo', e);
    if (e.detail.userInfo) {
      const jsCodeRes = await getApp().CommonHttp().mrjAsyncWXLogin({});
      if (jsCodeRes.code == null || jsCodeRes.code.length == 0) {
        this.showToast()
        return
      }
      const acc = wx.getAccountInfoSync()
      const {
        miniProgram
      } = acc;
      if (miniProgram == null) {
        this.showToast()
        return
      }
      const {
        appId
      } = miniProgram
      const param = {
        programId: appId,
        jsCode: jsCodeRes.code

      }
      const sessionKeyRes = await getApp().CommonHttp().loadSessionKey(param);
      if (sessionKeyRes == null || sessionKeyRes.result == null) {
        this.showToast()
        return
      }
      const {
        iv,
        encryptedData
      } = e.detail;
      const devodeParam = {
        iv,
        data: encryptedData,
        sessionKey: sessionKeyRes.result
      }
      const decodeRes = await getApp().CommonHttp().commonWXDecode(devodeParam)
      if (decodeRes.status == 200&&decodeRes.result!=null) {
        this.setData({
          userInfo: decodeRes.result,
          checked: !this.data.checked
        })
      } else {
        this.showToast()
      }
    }
  },
  showToast: function () {
    wx.showToast({
      title: '获取失败,请重试',
      icon: 'none'
    })
  },
  wxCheckSession: function () {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: (res) => {
          console.log(res);
          return resolve(true)
        },
        fail: f => {
          console.log(f);
          return resolve(false)
        }
      })
    })
  },
  submit: async function () {
    // 检查是否注册过了
    const {
      userInfo
    } = this.data;
    const {
      unionId
    } = userInfo;
    const data = await getApp().CommonHttp().checkUnionIdStatus({
      unionId
    });
     debugger
    if (data.status == 200) {
      if (data.result == false) {
        wx.navigateTo({
          url: './regist',
          success: res => {
            res.eventChannel.emit('dataSource', this.data.userInfo)
          },
          events: {
            callback: data => this.jumpReluanch(data)
          }
        })
      } else {
        const loginRes = await  getApp().CommonHttp().asyncLoginWithUnionId({
          unionId
        });
         
        if (loginRes.status == 200) {
          this.jumpReluanch(loginRes.result)
        }
      }

    } else {

    }
  },
  jumpReluanch: function (data) {
    const {
      merchantId,
      token,
      userId
    } = data
    wx.setStorageSync(MRDCommonConst.merchantIdKey, merchantId);
    wx.setStorageSync(MRDCommonConst.loginTokenKey, token);
    wx.setStorageSync(MRDCommonConst.userIdKey, userId);
    getApp().reLaunch()
  }
})